import React from "react";
import { NativeModules, Platform } from "react-native";

import Config from "../config";
import Constants from "../common/Constants";
import ToastUtils from "../common/ToastUtils";
import BaseModelNew from "./BaseModelNew";
import ImageUtil from "../pages/common/ImageUtil";
//用户数据
export default class SportModel extends BaseModelNew {
  constructor() {
    super();

    this.readHealthyKitData = this.readHealthyKitData.bind(this);
    this.sendSteps = this.sendSteps.bind(this);
    this.requestUserList = this.requestUserList.bind(this);
    this.requestSelfData = this.requestSelfData.bind(this);
    this.requestSelfListData = this.requestSelfListData.bind(this);
    this._sendStepsReadSteps = this._sendStepsReadSteps.bind(this);
    this.sendActivitySteps = this.sendActivitySteps.bind(this);
    this.sendActivityStepsDaily = this.sendActivityStepsDaily.bind(this);
    this.getTodayStep = this.getTodayStep.bind(this);
    this.sportJump = this.sportJump.bind(this);
    this.requestDibiaoSelfData = this.requestDibiaoSelfData.bind(this);
    this.requestDibiaoDetailSelfData = this.requestDibiaoDetailSelfData.bind(
      this
    );
    this.requestHealthConfig = this.requestHealthConfig.bind(this);
    this.getStepConfig = this.getStepConfig.bind(this);
    this.optionsStepConfig = this.optionsStepConfig.bind(this);

    this._healthyKit = null;
    this._healthyKitInit = false;
    this._healthDatas = { 0: { step: 0, distance: 0 } }; //{day:{step:0, distance:0}}
    this._callback = null;
    this._readDataSave = [];
    this._isReadingData = false;
    this.steps = { step: 0, distance: 0 };
  }
  // DqappStepDetail {
  //   all_rank (integer, optional): 油田内排行 ,
  //   by_name (string, optional): 用户名字 ,
  //   by_user_id (string, optional): 用户ID ,
  //   department (string, optional): 所属单位 ,
  //   department_rank (integer, optional): 部门内排行 ,
  //   steps (integer, optional): 步行数 ,
  //   updated_at (string, optional): 最后编辑时间
  //   }
  setup(dataManager, callback) {
    this.dataManager = dataManager;
    this._callback = callback;
    this._initHealthyKitData();
  }

  getTodayStep() {
    return this.steps;
  }

  //读取数据，  day == 0 表示今天  type step distance
  readHealthyKitData(actionData, callback) {
    //type, day
    let types = actionData.type;
    let day = actionData.day;
    if (this._healthyKitInit === true) {
      let type = "";
      for (var i = 0; i < types.length; i++) {
        type = types[i];
        this._dealReadHealthyKitData(type, day, callback);
      }
    } else {
      callback({});
    }
  }

  _dealReadHealthyKitData(type, day, callback) {
    if (!this._healthyKit) {
      return;
    }
    // ToastUtils.show("_dealReadHealthyKitData" + type + "   " + day);
    if (this._isReadingData === false) {
      this._isReadingData = true;
      if (this._healthDatas[day] === undefined) {
        this._healthDatas[day] = { step: 0, distance: 0 };
      }
      // if(day === 0 && type === "step") {
      // ToastUtils.show("请求=> 天：" + day);
      // }
      this._healthyKit.readHealthyKitData(type, day, params =>
        this._readHealthyKitDataCallback(params, day, type, callback)
      );
    } else {
      this._readDataSave.push({ type: type, day: day, callback: callback });
    }
  }

  _readHealthyKitDataCallback(params, day, type, callback) {
    // params = type === "distance" ? 10 + day : params;
    // if(day === 0 && type === "step") {
    // ToastUtils.show("返回=> type:" + type + "     值:" + params + "     天：" + day);
    // }
    // if(params < 0){
    //   params = 0;
    // }
    this._healthDatas[day][type] = params;
    if (params < 0 && type === "step") {
      // ImageUtil.uploadError(callback + " 步数计步log3：" + params);
    }

    console.log(
      "_readHealthyKitDataCallback",
      params,
      day,
      type,
      this._healthDatas
    );
    callback(this._healthDatas[day]);
    this._isReadingData = false;
    if (this._readDataSave.length > 0) {
      let data = this._readDataSave.shift();
      this._dealReadHealthyKitData(data.type, data.day, data.callback);
    }
  }

  _initHealthyKitData() {
    console.log("initHealthyKitData");
    if (Platform.OS === "android") {
      this._healthyKit = NativeModules.XPJPedometerUtil;
      this._initHealthyKitDataCallback("1");
    } else {
      this._healthyKit = NativeModules.HealthyKit;
      if (this._healthyKit) {
        this._healthyKit.initHealthyKitData(
          this._initHealthyKitDataCallback.bind(this)
        );
      } else {
        this._initHealthyKitDataCallback("1");
      }
    }
  }

  _initHealthyKitDataCallback(result) {
    // ToastUtils.show("initHealthyKitDataCallback " + result);
    console.log("initHealthyKitDataCallback result ", result);
    this._healthyKitInit = result === "1";
    this._callback();

    this.sendSteps();
    this._sendStepsInterval = setInterval(() => {
      this.sendSteps();
    }, 60 * 1000);
  }

  //http://118.89.111.124:8080/dqapp/health/steps
  //发送自己的步数
  sendSteps(callback) {
    let self = this;
    if (Platform.OS === "android") {
      // ToastUtils.show("requestSelfData");
      this.requestSelfData(null, function(data, isSucceed) {
        // ToastUtils.show("requestSelfData back:" + JSON.stringify(data) + isSucceed);
        if (!isSucceed) {
          return;
        }
        if (
          isSucceed &&
          data &&
          data.steps &&
          data.steps != 0 &&
          data.updated_at != ""
        ) {
          // ToastUtils.show("requestSelfData back 11" + JSON.stringify(data));
          //如果服务器已经有当天数据了，要和当天数据做比较
          // ToastUtils.show("读取步数：" + data.steps + "   " + data.updated_at);
          self._healthyKit.readHealthyKitDataAndSyn(
            data.steps,
            data.updated_at,
            step => {
              // ToastUtils.show("readHealthyKitDataAndSyn back " + step);
              // step = 25000;
              if (step > 0) {
                self._sendStepsReadSteps({ step: step }, callback);
                self.steps = { step: step };
              } else {
                ImageUtil.uploadError("步数计步log1：" + step);
              }
            }
          );
          return;
        } else {
          // ToastUtils.show("requestSelfData back 22");
          //如果服务器的数据也为0或者获取不到数据，正常计算
          self._dealReadHealthyKitData("step", 0, step => {
            // ToastUtils.show("_dealReadHealthyKitData back 22" + JSON.stringify(step));
            // step = {step:25000};
            if (step && step.step > 0) {
              self._sendStepsReadSteps(step, callback);
              self.steps = step;
            } else {
              //  ImageUtil.uploadError("步数计步log2："+ JSON.stringify(step));
            }
          });
        }
      });
    } else {
      // ToastUtils.show("dealReadHealthyKitData");
      this._dealReadHealthyKitData("step", 0, healthyData => {
        // ToastUtils.show("dealReadHealthyKitData back " + this.steps.step + "    " + healthyData.step);
        // healthyData = {step:25000};
        if (this.steps.step != healthyData.step) {
          this._sendStepsReadSteps(healthyData, callback);
        }
      });
      this._dealReadHealthyKitData("distance", 0, healthyData => {
      });
    }
  }

  //android  {“step”:0, “distance”:0}
  _sendStepsReadSteps(healthyData, callback) {
    // ToastUtils.show("sendStepsReadSteps" + JSON.stringify(healthyData));
    this.steps = healthyData;
    let url = Config.serverUrl + "/health/steps";
    let sendData = {};
    sendData.steps = healthyData.step;
    // sendData.steps = 3002;
    var date = new Date();
    // ToastUtils.show("发送协议前" + date.getHours());
    var hours = date.getHours();
    var minutes = date.getMinutes();
    if (date.getHours() == 23) {
      if (date.getMinutes() >= 50) {
        // ToastUtils.show("错误1" + date.getHours());
        return;
      }
    }
    if (date.getHours() == 0) {
      if (date.getMinutes() <= 10) {
        // ToastUtils.show("错误2" + date.getMinutes());
        return;
      }
    }
    sendData.client_report_at = date.getTime();
    sendData.client_report_at = parseInt(sendData.client_report_at / 1000);
    // ToastUtils.show("发送协议" + url + JSON.stringify(sendData));
    this.sendPost(url, JSON.stringify(sendData), callback);
  }

  //http://118.89.111.124:8080/dqapp/health/steps/config
  //请求列表
  //排序方式，1油田内，2部门内
  getStepConfig(data, callback) {
    const url = Config.serverUrl + "/health/steps/config";
    this.sendGet(url, callback);
  }

  optionsStepConfig(data, callback) {
    const url = Config.serverUrl + "/health/steps/config";
    this.sendPost(url, data, callback);
  }

  //http://118.89.111.124:8080/dqapp/health/steps?page=1&page_size=5&sort_id=1
  //请求列表
  //排序方式，1油田内，2部门内
  requestUserList(data, callback) {
    let page_size = data.page_size === undefined ? 10 : data.page_size;
    let url =
      Config.serverUrl +
      "/health/steps2?page=" +
      data.page +
      "&page_size=" +
      page_size +
      "&sort_id=" +
      data.sort_id +
      "&type=" +
      data.type;
    this.sendGet(url, callback);
  }

  //http://118.89.111.124:8080/dqapp/health/steps/owned
  //自己的数据
  requestSelfData(data, callback) {
    let url = Config.serverUrl + "/health/steps/owned2";
    this.sendGet(url, callback);
  }

  requestSelfListData(data, callback) {
    let url = Config.serverUrl + "/health/steps/list_owned2?page=1&page_size=10";
    this.sendGet(url, callback);
  }
  // 提交步数
  sendActivityStepsDaily(data, callback) {
    let url = Config.serverUrl + "/health/steps";
    var date = new Date();
    data.client_report_at = date.getTime();
    this.sendPost(url, data, callback);
  }
  //http://118.89.111.124/dqapp/health/steps/submit
  sendActivitySteps(data, callback) {
    let url = Config.serverUrl + "/health/steps/submit";
    var date = new Date();
    data.client_submit_at = date.getTime();
    this.sendPost(url, data, callback);
  }
  sportJump(data, callback) {
    let url = Config.serverUrlHttps + "/app/sport_jump";
    this.sendGet(url, callback);
  }
  //请求油田地标自己的数据
  //http://118.89.111.124/dqapp/landmarks
  requestDibiaoSelfData(data, callback) {
    let url = Config.serverUrl + "/landmarks";
    this.sendGet(url, callback);
  }
  requestHealthConfig(data, callback) {
    let url = Config.serverUrl + "/health/steps/sys_config";
    this.sendGet(url, callback);
  }
  requestDibiaoDetailSelfData(data, callback) {
    let url =
      Config.serverUrl +
      "/landmarks/" +
      data.user_id +
      "/" +
      data.landmark_id +
      "/public";
    this.sendGet(url, callback);
  }
}
